package com.example.demo.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 针对bean对象进行字段获取拷贝等操作.
 *
 * @author
 * @modify lance
 * <p>
 * 2012-4-19
 */
public class BeanUtils extends org.springframework.beans.BeanUtils {

    protected static Log logger = LogFactory.getLog(BeanUtils.class);


    public static Field getDeclaredField(Object object, String propertyName) throws NoSuchFieldException {
        Assert.notNull(object, "target object must not be null");
        Assert.hasText(propertyName, "property name must not be null");
        return getDeclaredField(object.getClass(), propertyName);
    }

    /**
     * 获取某个类的某个名称的定义域
     *
     * @param clazz        类
     * @param propertyName 属性名
     * @return 定义域
     * @throws NoSuchFieldException
     */
    @SuppressWarnings("rawtypes")
    public static Field getDeclaredField(Class clazz, String propertyName) throws NoSuchFieldException {
        Assert.notNull(clazz, "Class type must not be null");
        Assert.hasText(propertyName, "property name must not be null");
        for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            return superClass.getDeclaredField(propertyName);
        }
        throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + propertyName);
    }

    private static List<Field> getCurrentClassDeclaredFields(Class clazz, Class annotation) {
        Assert.notNull(clazz, "Class type must not be null");
        Assert.notNull(annotation, "annotation must not be null");
        List<Field> fields = new ArrayList<Field>();

        for (Field f : clazz.getDeclaredFields()) {
            if (f.getAnnotation(annotation) != null) {
                fields.add(f);
            }
        }
        return fields;
    }

    public static List<Field> getDeclaredFields(Class clazz, Class annotation) {
        Assert.notNull(clazz, "Class type must not be null");
        Assert.notNull(annotation, "annotation must not be null");
        List<Field> fields = new ArrayList<Field>();
        for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            List<Field> l = getCurrentClassDeclaredFields(superClass, annotation);
            fields.addAll(l);
        }

        return fields;
    }

    /**
     * 强制获取某个属性值<p>
     * 该操作将手动设置公有私有约束<p>
     *
     * @param object       对象
     * @param propertyName 属性值
     * @return 数值
     * @throws NoSuchFieldException
     */
    public static Object forceGetProperty(Object object, String propertyName) throws NoSuchFieldException {
        Assert.notNull(object, "target object must not be null");
        Assert.hasText(propertyName, "property name must not be null");

        Field field = getDeclaredField(object, propertyName);

        boolean accessible = field.isAccessible();
        field.setAccessible(true);

        Object result = null;
        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            logger.info("error wont' happen");
        }
        field.setAccessible(accessible);
        return result;
    }

    /**
     * 强制设置某个属性域<p>
     * 该操作将手动设置公有私有约束<p>
     *
     * @param object       对象
     * @param propertyName 属性名称
     * @param newValue     新值
     * @throws NoSuchFieldException
     */
    public static void forceSetProperty(Object object, String propertyName, Object newValue)
            throws NoSuchFieldException {
        Assert.notNull(object, "target object must not be null");
        Assert.hasText(propertyName, "property name must not be null");

        Field field = getDeclaredField(object, propertyName);
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        try {
            field.set(object, newValue);
        } catch (IllegalAccessException e) {
            logger.info("Error won't happen");
        }
        field.setAccessible(accessible);
    }

    /**
     * 强制执行某个方法<p>
     * 该操作将手动设置公有私有约束<p>
     *
     * @param object     被执行对象
     * @param methodName 方法名称
     * @param params     参数
     * @return
     * @throws NoSuchMethodException
     */
    @SuppressWarnings("rawtypes")
    public static Object forceInvokeMethod(Object object, String methodName, Object... params)
            throws NoSuchMethodException {
        Assert.notNull(object, "target object must not be null");
        Assert.hasText(methodName, "methodName name must not be null");
        Class[] types = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            types[i] = params[i].getClass();
        }

        Class clazz = object.getClass();
        Method method = null;
        for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                method = superClass.getDeclaredMethod(methodName, types);
                break;
            } catch (NoSuchMethodException e) {

            }
        }

        if (method == null)
            throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);

        boolean accessible = method.isAccessible();
        method.setAccessible(true);
        Object result = null;
        try {
            result = method.invoke(object, params);
        } catch (Exception e) {
            ReflectionUtils.handleReflectionException(e);
        }
        method.setAccessible(accessible);
        return result;
    }

    private static String mapPrint(Map<?, ?> tgt) {
        if (tgt == null)
            return null;

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Object key : tgt.keySet()) {

            sb.append(key + ":" + objectPrint(tgt.get(key)) + ";");
        }
        sb.append("}");
        return sb.toString();
    }

    public static String objectPrint(Object tgt) {
        if (tgt == null)
            return null;

        if (tgt.getClass().isArray()) {
            return arrayPrint(tgt);
        } else if (!tgt.getClass().isSynthetic()) {
            if (tgt instanceof Collection) {
                return collectionPrint((Collection<?>) tgt);
            } else if (tgt instanceof Map) {
                return mapPrint((Map<?, ?>) tgt);
            } else if (tgt instanceof Number) {
                return tgt.toString();
            } else if (tgt instanceof CharSequence) {
                return tgt.toString();
            } else if (tgt instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                return sdf.format(tgt);
            } else {
                return beanPrint(tgt);
            }
        } else if (tgt.getClass().isEnum()) {
            return enumPrint(tgt);
        } else {
            return tgt.toString();
        }
    }

    private static String enumPrint(Object tgt) {
        if (tgt == null)
            return null;

        return tgt.toString();
    }

    private static String arrayPrint(Object tgt) {
        if (tgt == null)
            return null;

        int length = Array.getLength(tgt);
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        boolean isfirst = true;
        for (int i = 0; i < length; i++) {
            if (!isfirst) {
                sb.append(",");
            } else {
                isfirst = false;
            }
            sb.append(objectPrint(Array.get(tgt, i)));
        }
        sb.append("]");
        return sb.toString();
    }

    private static String beanPrint(Object tgt) {
        if (tgt == null)
            return null;

        List<Field> fields = new ArrayList<Field>();
        for (Class<?> superClass = tgt.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            fields.addAll(Arrays.asList(superClass.getDeclaredFields()));
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object o = field.get(tgt);
                sb.append(field.getName() + ":" + objectPrint(o) + ";");
            } catch (Exception e) {
                ReflectionUtils.handleReflectionException(e);
            }
        }
        sb.append("}");
        return sb.toString();
    }


    private static String collectionPrint(Collection<?> tgt) {
        if (tgt == null)
            return null;

        StringBuilder sb = new StringBuilder();
        sb.append("[");
        boolean isfirst = true;
        for (Object o : tgt) {
            if (!isfirst) {
                sb.append(",");
            } else {
                isfirst = false;
            }
            sb.append(objectPrint(o));
        }
        sb.append("]");
        return sb.toString();
    }

    public static final void main(String[] args) {
        class Symbol {
            private int[] a = {1, 2, 3, 4, 5};
            private String b = "test";
        }
        class TestClass {
            private List<Symbol> c = new ArrayList<Symbol>();
            private Symbol d = new Symbol();
        }
        System.out.println(objectPrint(new TestClass()));
    }
}
